package com.topcoder.tco305;

import java.util.ArrayList;

public class PlayingCubes {
	public int[] composeWords(String[] cubes, String[] words) {
		ArrayList<Integer> answer = new ArrayList<Integer>();
		
		for (int i=0; i<words.length; i++) {
			if (canDo(cubes, words[i], new boolean[cubes.length])) answer.add(i);
		}
		
		int[] a = new int[answer.size()];
		for (int i=0; i<answer.size(); i++) a[i] = answer.get(i);
		return a;
	}
	
	private boolean canDo(String[] cubes, String word, boolean[] used) {
		if (word.length() == 0) return true;
		for (int i=0; i<cubes.length; i++) {
			if (!used[i] && cubes[i].indexOf(word.charAt(0))>=0) {
				used[i] = true;
				if (canDo(cubes, word.substring(1), used)) return true;
				used[i] = false;
			}
		}
		return false;
	}
}
